package com.lyk.read.book.dialog

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.hjq.toast.ToastUtils
import com.lyk.common.manager.GlideManager
import com.lyk.common.util.FileUtil
import com.lyk.common.util.FileUtil.CopyListener
import com.lyk.common.util.GsonUtil.toJson
import com.lyk.common.util.ResourcesUtil
import com.lyk.common.util.WindowUtil
import com.lyk.common.util.WindowUtil.dp
import com.lyk.photo.PhotoManager
import com.lyk.photo.activity.PhotoAlbumActivity
import com.lyk.photo.entity.LocalMedia
import com.lyk.photo.entity.PhotoParam
import com.lyk.read.book.bean.DetailItemBean
import com.lyk.read.book.bean.ItemBean
import com.lyk.read.book.databinding.DialogAddOrEditBinding
import com.lyk.read.book.util.Util
import java.io.File
import kotlin.math.min

/**
 * Created by LianYongKe on 2024/3/18.
 */
class AddOrEditDialog : BaseBindingDialog<DialogAddOrEditBinding>() {

    override fun getDialogWidth(): Int {
        return WindowUtil.getScreenWidth() - 20.dp
    }

    override fun getBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): DialogAddOrEditBinding {
        return DialogAddOrEditBinding.inflate(inflater, container, false)
    }

    var myConfirmCallBack: ((bean: ItemBean) -> Unit)? = null
    var detailConfirmCallBack: ((bean: DetailItemBean) -> Unit)? = null

    /**
     * 0 add itemBean，1 change itemBean，2 add DetailItemBean
     */
    private var type: Int = 0
    private var imagePath: String? = null

    private val launcher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode != AppCompatActivity.RESULT_OK) {
                return@registerForActivityResult
            }

            val imageBean = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                it.data?.getParcelableExtra(PhotoManager.INTENT_CONFIRM, LocalMedia::class.java)
            } else {
                it.data?.getParcelableExtra(PhotoManager.INTENT_CONFIRM)
            }
            imagePath = imageBean?.cropPath
            GlideManager.loadImage(context, binding.dialogImage, imagePath ?: "")
        }

    override fun initView() {
        type = arguments?.getInt("type", 0) ?: 0

        if (type == 1) {
            setItemData()
        } else if (type == 2){
            setDetailData()
            binding.dialogDesc.visibility = View.GONE
        }

        binding.dialogTitle.setOnClickListener {
            if (type != 1) {
                showEditDialog(binding.dialogTitle)
            }
        }
        binding.dialogDesc.setOnClickListener {
            showEditDialog(binding.dialogDesc)
        }
        binding.dialogImage.setOnClickListener {
            val param = PhotoParam()
            param.showType = 1
            param.cameraType = 2
            param.canSelectCount = 1
            param.cropShape = 1
            launcher.launch(
                Intent(context, PhotoAlbumActivity::class.java).apply {
                    putExtra(PhotoManager.INTENT_AlBUM, param)
                }
            )
        }
        binding.dialogCancel.setOnClickListener {
            dismiss()
        }
        binding.dialogConfirm.setOnClickListener {
            imagePath?.let {

                // cropPath 已经在想要的文件夹中了，就先不复制了

                val title = binding.dialogTitle.text.toString().trim()
                if (type == 2) {
                    detailConfirmCallBack?.invoke(DetailItemBean(title, it))
                } else {
                    val desc = binding.dialogDesc.text.toString().trim()
                    myConfirmCallBack?.invoke(ItemBean(title, desc, it))
                }
                dismiss()

//                val out = Util.getPicPath()
//
//                // 复制图片
//                FileUtil.copy(File(it), out, object : CopyListener {
//                    override fun onProgressUpdate(p0: Double) {
//                    }
//
//                    override fun onSuccess(p0: File?) {
//                        onConfirmCallBack?.onConfirm(p0.toString())
//                    }
//
//                    override fun onFail(p0: Int) {
//                        ToastUtils.show("存储图片失败，请重试")
//                    }
//
//                })

            } ?: ToastUtils.show("需要图片哦！")
        }
    }

    private fun setItemData() {
        val bean = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getParcelable("mainItem", ItemBean::class.java)
        } else {
            @Suppress("DEPRECATION") arguments?.getParcelable("mainItem")
        }

        bean?.let {
            binding.dialogTitle.text = it.title
            binding.dialogDesc.text = it.desc
            imagePath = it.img
            GlideManager.loadImage(context, binding.dialogImage, it.img ?: "")
        }
    }

    private fun setDetailData() {
        val bean = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getParcelable("detailItem", DetailItemBean::class.java)
        } else {
            @Suppress("DEPRECATION") arguments?.getParcelable("detailItem")
        }

        bean?.let {
            binding.dialogTitle.text = it.desc
            imagePath = it.img
            GlideManager.loadImage(context, binding.dialogImage, it.img ?: "")
        }
    }

    private fun showEditDialog(textView: TextView) {
        EditDialog().apply {
            arguments = Bundle().apply {
                putString("data", textView.text.toString())
            }
            onConfirmCallBack = object : ConfirmCallBack {
                override fun onConfirm(value: String) {
                    textView.text = value
                }
            }
            showDialog(this, "")
        }
    }
}